package com.googlecode.serialization;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class DataInfo {
	/**
	 * Maximum data size allowed by memcached.
	 */
	public static final int MAX_SIZE = 1024 * 1024;

	private int flag;
	private byte[] data;
	private long cas;
	private int capacity = -1;
	private int size = 0;
	
	/**
	 * Get a DataInfo instance for the given flags and byte array.
	 * 
	 * @param f
	 *            the flags
	 * @param d
	 *            the data
	 * @param capacity
	 *            the maximum allowable size.
	 */
	public DataInfo(int flag, byte[] data, int capacity, long casId) {
		super();
		this.capacity = capacity;
		this.size = (data != null) ? data.length : 0;
		if (data != null && data.length > capacity) {
			throw new IllegalArgumentException(String.format(
					"Cannot cache data larger than %d byte (you tried to cache a %d byte object)", MAX_SIZE, data.length));
		}
		this.flag = flag;
		this.data = data;
		this.cas = casId;
	}
	/**
	 * Get a DataInfo instance for the given flags and byte array.
	 * 
	 * @param f
	 *            the flags
	 * @param d
	 *            the data
	 */
	public DataInfo(int flag, byte[] data) {
		this(flag, data, MAX_SIZE, -1);
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		if (data.length > this.capacity) {
			throw new IllegalArgumentException(String.format(
					"Cannot cache data larger than %d byte (you tried to cache a %d byte object)", MAX_SIZE, data.length));
		}
		this.data = data;
	}

	public long getCas() {
		return cas;
	}

	public void setCas(long cas) {
		this.cas = cas;
	}

	public int getCapacity() {
		return capacity;
	}

	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public static int getMaxSize() {
		return MAX_SIZE;
	}

	public final void fillData(ByteBuffer buffer, int offset, int length) {
		buffer.get(this.data, offset, length);
		this.size += length;
	}

	public final void fillData(ByteBuffer buffer, int length) {
		buffer.get(this.data, this.size, length);
		this.size += length;
	}

	public int remainingCapacity() {
		return (this.capacity < 0) ? -1 : (this.capacity - this.size);
	}
	
	@Override
	public String toString() {
		return "DataInfo [capacity=" + capacity + ", cas=" + cas + ", data=" + Arrays.toString(data) + ", flag=" + flag
				+ ", size=" + size + "]";
	}
}
